package com.nfit.rabbitmq.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * ClassName:TopicProducer
 * Package:com.nfit.rabbitmq.producer
 * Description
 *
 * @Author L
 * @Create 2024/11/21 15:57
 */
public class TopicProducer {

    /**
     * 自定义交换机名称
     */
    private static final String EXCHANGE_NAME = "test.topic";


    public static void main(String[] args) {
        //初始化链接工厂并设置rabbitmq的主机地址
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672); //通信接口,1572是rabbitmq端口
        factory.setUsername("guest");
        factory.setPassword("guest");

        //创建链接
        try (Connection conn = factory.newConnection()){
            //使用链接构建一个通信通道
            Channel channel = conn.createChannel();
            //创建交换机
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC,false);

            //定义消息
            String messageA = "Hello World! ";
            String messageB = "Hello World! rabbitmq-projuct";

            /**
             * 将消息投递到交换机,并指定不同的路由key
             * 发布消息
             * 参数一：设置为""，表示未指定交换机的名称，此时会通过一个默认的交换机来路由消息
             * 参数二：队列名称
             * 参数三：消息路由头的其他属性，这里未添添加任何属性，设置为null
             * 参数四：消息体，将其转换为字节数组
             */
            channel.basicPublish(EXCHANGE_NAME, "a.key", null, messageA.getBytes());
            channel.basicPublish(EXCHANGE_NAME, "b.key", null, messageB.getBytes());
        }catch (Exception e){
            throw new RuntimeException("Can't connect to RabbitMQ");
        }
    }
}
